package com.flame.workflow.ru.engine.handler;

import java.util.List;

import com.flame.workflow.constants.RuntimeConstants;
import com.flame.workflow.constants.TaskConstants;
import com.flame.workflow.re.entity.Node;
import com.flame.workflow.ru.engine.context.RuntimeContext;
import com.flame.workflow.ru.entity.Instance;
import com.flame.workflow.ru.entity.Task;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

/**
 * @author wuxintong😺😺😺
 * @since 2023/6/6
 */
@Service("workflow-parallel-branch-task-handler")
public class ParallelBranchTaskHandler extends AbstractTaskHandler {

    @Override
    public String runTask(RuntimeContext runtimeContext) {
        Instance instance = runtimeContext.getInstance();
        Task task = runtimeContext.getTask();
        Task dbTask = taskService.getTask(task.getTaskId());

        if (RuntimeConstants.RUNTIME_STATUS_WAIT.equals(dbTask.getTaskStatus())) {
            boolean flag = true;
            List<Task> branchTaskList = taskService.listByBranchTaskId(dbTask.getTaskId());
            for (Task branchTask : branchTaskList) {
                if (!RuntimeConstants.RUNTIME_STATUS_COMPLETE.equals(branchTask.getTaskStatus())) {
                    flag = false;
                    break;
                }
            }
            if (!flag) {
                return RuntimeConstants.RUNTIME_STATUS_WAIT;
            }
            return RuntimeConstants.RUNTIME_STATUS_COMPLETE;
        } else if (RuntimeConstants.RUNTIME_STATUS_COMPLETE.equals(dbTask.getTaskStatus())) {
            return RuntimeConstants.RUNTIME_STATUS_COMPLETE;
        } else {
            List<Node> nodeList = nodeService.listByParentId(instance.getModelId(), instance.getModelVersion(), task.getNodeId());
            if (CollectionUtils.isEmpty(nodeList)) {
                return RuntimeConstants.RUNTIME_STATUS_COMPLETE;
            }
            return RuntimeConstants.RUNTIME_STATUS_WAIT;
        }
    }

    @Override
    public String taskType() {
        return TaskConstants.TASK_TYPE_PARALLEL_BRANCH;
    }
}
